import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { inventory, products } from '@/lib/schema';
import { eq, and, sql } from 'drizzle-orm';

export async function GET() {
  try {
    const inventoryData = await db
      .select({
        id: inventory.id,
        productId: inventory.productId,
        quantity: inventory.quantity,
        lowStockThreshold: inventory.lowStockThreshold,
        updatedAt: inventory.updatedAt,
        productName: products.name,
        productSku: products.sku,
        productPrice: products.price,
      })
      .from(inventory)
      .leftJoin(products, eq(inventory.productId, products.id));

    return NextResponse.json(inventoryData);
  } catch (error) {
    console.error('获取库存数据失败:', error);
    return NextResponse.json(
      { error: '获取库存数据失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const { productId, quantity, lowStockThreshold } = body;

    if (!productId || quantity === undefined) {
      return NextResponse.json(
        { error: '产品ID和库存数量不能为空' },
        { status: 400 }
      );
    }

    // 检查库存记录是否已存在
    const existingInventory = await db
      .select()
      .from(inventory)
      .where(eq(inventory.productId, productId))
      .limit(1);

    let result;
    
    if (existingInventory.length > 0) {
      // 更新现有库存
      result = await db
        .update(inventory)
        .set({
          quantity: quantity,
          lowStockThreshold: lowStockThreshold || existingInventory[0].lowStockThreshold,
          updatedAt: new Date(),
        })
        .where(eq(inventory.productId, productId))
        .returning();
    } else {
      // 创建新库存记录
      result = await db
        .insert(inventory)
        .values({
          productId: productId,
          quantity: quantity,
          lowStockThreshold: lowStockThreshold || 10,
          updatedAt: new Date(),
        })
        .returning();
    }

    return NextResponse.json(result[0], { status: 201 });
  } catch (error: any) {
    console.error('创建/更新库存失败:', error);
    
    if (error.message?.includes('FOREIGN KEY constraint failed')) {
      return NextResponse.json(
        { error: '产品不存在' },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { error: '创建/更新库存失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}